using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using LuaFramework;
using LuaInterface;
using UnityEngine;
using UnityEngine.Networking;

public class webglLua : MonoBehaviour
{
    LuaState lua = null;
    private LuaLoader loader = null;
    private string strLog = "";

    void Start()
    {
        Application.logMessageReceived += Log;
        loader = new LuaLoader();
        lua = new LuaState();
        InitLuaBundle(() =>
        {
            lua.Start();
            lua.DoFile("requireCommon.lua");
        });
        this.OpenLibs();
        lua.LuaSetTop(0);

        LuaBinder.Bind(lua);
        DelegateFactory.Init();
    }

    /// <summary>
    /// 初始化加载第三方库
    /// </summary>
    void OpenLibs()
    {
#if UNITY_WEBGL
        //webgl 中无法使用这些，会报错.
        return;
#endif
        lua.OpenLibs(LuaDLL.luaopen_pb);
        lua.OpenLibs(LuaDLL.luaopen_sproto_core);
        lua.OpenLibs(LuaDLL.luaopen_protobuf_c);
        lua.OpenLibs(LuaDLL.luaopen_lpeg);
        lua.OpenLibs(LuaDLL.luaopen_bit);
        lua.OpenLibs(LuaDLL.luaopen_socket_core);
        this.OpenCJson();
    }

    protected void OpenCJson()
    {
        lua.LuaGetField(LuaIndexes.LUA_REGISTRYINDEX, "_LOADED");
        lua.OpenLibs(LuaDLL.luaopen_cjson);
        lua.LuaSetField(-2, "cjson");

        lua.OpenLibs(LuaDLL.luaopen_cjson_safe);
        lua.LuaSetField(-2, "cjson.safe");
    }

    /// <summary>
    /// 初始化LuaBundle
    /// </summary>
    void InitLuaBundle(Action back)
    {
        if (loader.beZip)
        {
#if UNITY_WEBGL
            StartCoroutine(_AddBundle("lua/lua.unity3d", back));
#else
            loader.AddBundle("lua/lua.unity3d");
            back.Invoke();
#endif
            Debug.Log("InitLuaBundle finished");
        }
    }

    public IEnumerator _AddBundle(string bundleName, Action back)
    {
        yield return 0;
        var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, bundleName));
        UnityWebRequest request = UnityWebRequest.Get(uri);
        yield return request.SendWebRequest();
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            AssetBundle ab = AssetBundle.LoadFromMemory(request.downloadHandler.data);
            loader.AddBundle(bundleName, ab);
        }

        back.Invoke();
    }


    void Log(string msg, string stackTrace, LogType type)
    {
        strLog += msg;
        strLog += "\r\n";
    }

    private string luastr = "print(123);log(456)";
    private string luaFile = "test.lua";

    void OnGUI()
    {
        GUILayout.Label(" hello, 'requireCommon.lua' help we require some common interface...," +
                        "log(),logError(),find(),GameObject...,GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube)");
        GUILayout.Label("DoString:", GUILayout.Width(100));
        luastr = GUILayout.TextArea(luastr, GUILayout.Width(300), GUILayout.Height(80));

        GUILayout.Label("DoFile:", GUILayout.Width(100));
        luaFile = GUILayout.TextField(luaFile, GUILayout.Width(200), GUILayout.Height(50));
        if (GUILayout.Button("DoString", GUILayout.Width(100), GUILayout.Height(40)))
        {
            strLog = "";
            lua.DoString(luastr);
        }

        if (GUILayout.Button("DoFile", GUILayout.Width(100), GUILayout.Height(40)))
        {
            strLog = "";
            lua.DoFile(luaFile);
        }

        GUILayout.Label(strLog);
    }

    void OnApplicationQuit()
    {
        lua.Dispose();
        lua = null;
        Application.logMessageReceived -= Log;
    }
}